package com.jrx.anytxn.reporting.job.reportingFile.config;

import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.ReportingFileConfig;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.job.reportingFile.step.MergeReportingFileListener;
import com.jrx.anytxn.reporting.service.IReportingFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(ReportingFileConfig.class)
public class MergeReportingFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MergeReportingFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private ReportingFileConfig reportingFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IReportingFileService reportingFileService;
    @Autowired
    private MergeReportingFileListener mergeReportingFileListener;

    @Bean
    public Job mergeReportingFileJob(){
        return jobBuilderFactory.get("mergeReportingFileJob")
                .listener(mergeReportingFileListener)
                .start(mergeReportingFileStep())
                .build();
    }

    @Bean
    public Step mergeReportingFileStep() {
        return stepBuilderFactory.get("mergeReportingFileStep")
                .tasklet(mergeReportingFileStepTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeReportingFileStepTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("分库文件合并开始。。。。。。");
            String filePath = reportingFileConfig.getReportingFilePath();
            String fileName = reportingFileConfig.getReportingFileName();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
            reportingFileService.mergeFile(org,filePath,fileName);

            logger.debug("报送分库文件合并处理完成");
            return RepeatStatus.FINISHED;
        };
    }
}
